package com.boil.qz.safekavass.shiro.filter;

import com.boil.util.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by ChenYong on 2017-04-14.
 * <br>
 * 上一次请求过滤器。
 * <br>
 * 排除请求：Ajax 请求/JSON 请求/错误页面请求。
 */
public class PrevRequestFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 获取请求
        HttpServletRequest request1 = (HttpServletRequest) request;
        // 请求路径
        String servletPath = (StringUtils.isBlank(request1.getServletPath()) ? Constants.EMPTY_STR : request1.getServletPath());

        // 如果是 GET 请求，且非 Ajax 请求/非 JSON 请求/非登录请求/非退出登录请求/非错误页面请求
        if (StringUtils.isNotBlank(servletPath) && //
                Constants.REQUEST_GET.equalsIgnoreCase(request1.getMethod()) && //
                !Constants.AJAX_REQUEST.equalsIgnoreCase(request1.getHeader(Constants.REQUEST_TYPE)) && //
                !servletPath.endsWith(Constants.SUFFIX_JSON) && //
                !Constants.URL_LOGIN.equals(servletPath) && //
                !Constants.URL_LOGOUT.equals(servletPath) && //
                !Constants.URL_403.equals(servletPath) && //
                !Constants.URL_403_1.equals(servletPath) && //
                !Constants.URL_404.equals(servletPath) && //
                !Constants.URL_404_1.equals(servletPath) && //
                !Constants.URL_412.equals(servletPath) && //
                !Constants.URL_500.equals(servletPath)) {
            // 获取登录用户的操作信息
            Subject subject = SecurityUtils.getSubject();
            // 获取 Session
            Session session = subject.getSession();
            // 请求参数
            String queryString = request1.getQueryString();

            if (StringUtils.isNotBlank(queryString)) {
                servletPath = String.format("%s?%s", servletPath, queryString);
            }

            session.setAttribute(Constants.PREV_REQUEST_URL, servletPath);
        }

        chain.doFilter(request, response);
    }
}